package com.jake.xfeed.multistate;

import androidx.annotation.NonNull;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;


public class MultiStater {
    public enum State {INIT, EMPTY, ERROR, LOADING, SUCCESS}

    protected final Set<MultiStateListener> mListeners = new HashSet<>();
    protected State mState = State.INIT;

    public void update(State state, Map<String, Object> params) {
        if (state == null || state == mState) {
            return;
        }
        onUpdate(state, mState, params);
        mState = state;
    }

    private void onUpdate(State newState, State oldState, Map<String, Object> params) {
        for (MultiStateListener listener : mListeners) {
            if (listener != null) {
                listener.onStateChanged(newState, oldState, params);
            }
        }
    }

    public void addListener(MultiStateListener listener) {
        if (listener != null) {
            mListeners.add(listener);
        }
    }

    public void removeListener(MultiStateListener listener) {
        if (listener != null) {
            mListeners.remove(listener);
        }
    }

    @NonNull
    public State getState() {
        return mState;
    }
}
